3 * Base classes for database-dumping maintenance scripts.
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
25 * @ingroup Maintenance
28 require_once __DIR__
. '/../Maintenance.php';
29 require_once __DIR__
. '/../../includes/export/WikiExporter.php';
31 use MediaWiki\MediaWikiServices
;
32 use Wikimedia\Rdbms\LoadBalancer
;
33 use Wikimedia\Rdbms\IDatabase
;
37 * @ingroup Maintenance
39 abstract class BackupDumper
extends Maintenance
{
40 public $reporting = true;
41 public $pages = null; // all pages
42 public $skipHeader = false; // don't output <mediawiki> and <siteinfo>
43 public $skipFooter = false; // don't output </mediawiki>
46 public $revStartId = 0;
48 public $dumpUploads = false;
49 public $dumpUploadFileContents = false;
50 public $orderRevs = false;
52 protected $reportingInterval = 100;
53 protected $pageCount = 0;
54 protected $revCount = 0;
55 protected $schemaVersion = null; // use default
56 protected $server = null; // use default
57 protected $sink = null; // Output filters
58 protected $lastTime = 0;
59 protected $pageCountLast = 0;
60 protected $revCountLast = 0;
62 protected $outputTypes = [];
63 protected $filterTypes = [];
68 * The dependency-injected database to use.
74 protected $forcedDb = null;
76 /** @var LoadBalancer */
80 * @param array|null $args For backward compatibility
82 function __construct( $args = null ) {
83 parent
::__construct();
84 $this->stderr
= fopen( "php://stderr", "wt" );
86 // Built-in output and filter plugins
87 $this->registerOutput( 'file', DumpFileOutput
::class );
88 $this->registerOutput( 'gzip', DumpGZipOutput
::class );
89 $this->registerOutput( 'bzip2', DumpBZip2Output
::class );
90 $this->registerOutput( 'dbzip2', DumpDBZip2Output
::class );
91 $this->registerOutput( 'lbzip2', DumpLBZip2Output
::class );
92 $this->registerOutput( '7zip', Dump7ZipOutput
::class );
94 $this->registerFilter( 'latest', DumpLatestFilter
::class );
95 $this->registerFilter( 'notalk', DumpNotalkFilter
::class );
96 $this->registerFilter( 'namespace', DumpNamespaceFilter
::class );
98 // These three can be specified multiple times
99 $this->addOption( 'plugin', 'Load a dump plugin class. Specify as <class>[:<file>].',
100 false, true, false, true );
101 $this->addOption( 'output', 'Begin a filtered output stream; Specify as <type>:<file>. ' .
102 '<type>s: file, gzip, bzip2, 7zip, dbzip2, lbzip2', false, true, false, true );
103 $this->addOption( 'filter', 'Add a filter on an output branch. Specify as ' .
104 '<type>[:<options>]. <types>s: latest, notalk, namespace', false, true, false, true );
105 $this->addOption( 'report', 'Report position and speed after every n pages processed. ' .
106 'Default: 100.', false, true );
107 $this->addOption( 'schema-version', 'Schema version to use for output. ' .
108 'Default: ' . WikiExporter
::schemaVersion(), false, true );
109 $this->addOption( 'server', 'Force reading from MySQL server', false, true );
110 $this->addOption( '7ziplevel', '7zip compression level for all 7zip outputs. Used for ' .
111 '-mx option to 7za command.', false, true );
114 // Args should be loaded and processed so that dump() can be called directly
115 // instead of execute()
116 $this->loadWithArgv( $args );
117 $this->processOptions();
122 * @param string $name
123 * @param string $class Name of output filter plugin class
125 function registerOutput( $name, $class ) {
126 $this->outputTypes
[$name] = $class;
130 * @param string $name
131 * @param string $class Name of filter plugin class
133 function registerFilter( $name, $class ) {
134 $this->filterTypes
[$name] = $class;
138 * Load a plugin and register it
140 * @param string $class Name of plugin class; must have a static 'register'
141 * method that takes a BackupDumper as a parameter.
142 * @param string $file Full or relative path to the PHP file to load, or empty
144 function loadPlugin( $class, $file ) {
148 $register = [ $class, 'register' ];
153 throw new MWException( 'execute() must be overridden in subclasses' );
157 * Processes arguments and sets $this->$sink accordingly
159 function processOptions() {
163 $this->schemaVersion
= WikiExporter
::schemaVersion();
165 $options = $this->orderedOptions
;
166 foreach ( $options as $arg ) {
167 list( $opt, $param ) = $arg;
171 $val = explode( ':', $param, 2 );
173 if ( count( $val ) === 1 ) {
174 $this->loadPlugin( $val[0], '' );
175 } elseif ( count( $val ) === 2 ) {
176 $this->loadPlugin( $val[0], $val[1] );
181 $split = explode( ':', $param, 2 );
182 if ( count( $split ) !== 2 ) {
183 $this->fatalError( 'Invalid output parameter' );
185 list( $type, $file ) = $split;
186 if ( !is_null( $sink ) ) {
189 if ( !isset( $this->outputTypes
[$type] ) ) {
190 $this->fatalError( "Unrecognized output sink type '$type'" );
192 $class = $this->outputTypes
[$type];
193 if ( $type === "7zip" ) {
194 $sink = new $class( $file, intval( $this->getOption( '7ziplevel' ) ) );
196 $sink = new $class( $file );
201 if ( is_null( $sink ) ) {
202 $sink = new DumpOutput();
205 $split = explode( ':', $param, 2 );
208 if ( !isset( $this->filterTypes
[$key] ) ) {
209 $this->fatalError( "Unrecognized filter type '$key'" );
212 $type = $this->filterTypes
[$key];
214 if ( count( $split ) === 1 ) {
215 $filter = new $type( $sink );
216 } elseif ( count( $split ) === 2 ) {
217 $filter = new $type( $sink, $split[1] );
220 // references are lame in php...
225 case 'schema-version':
226 if ( !in_array( $param, XmlDumpWriter
::$supportedSchemas ) ) {
228 "Unsupported schema version $param. Supported versions: " .
229 implode( ', ', XmlDumpWriter
::$supportedSchemas )
232 $this->schemaVersion
= $param;
237 if ( $this->hasOption( 'report' ) ) {
238 $this->reportingInterval
= intval( $this->getOption( 'report' ) );
241 if ( $this->hasOption( 'server' ) ) {
242 $this->server
= $this->getOption( 'server' );
245 if ( is_null( $sink ) ) {
246 $sink = new DumpOutput();
250 if ( count( $sinks ) > 1 ) {
251 $this->sink
= new DumpMultiWriter( $sinks );
257 function dump( $history, $text = WikiExporter
::TEXT
) {
258 # Notice messages will foul up your XML output even if they're
259 # relatively harmless.
260 if ( ini_get( 'display_errors' ) ) {
261 ini_set( 'display_errors', 'stderr' );
264 $this->initProgress( $history );
266 $db = $this->backupDb();
267 $exporter = new WikiExporter( $db, $history, $text );
268 $exporter->setSchemaVersion( $this->schemaVersion
);
269 $exporter->dumpUploads
= $this->dumpUploads
;
270 $exporter->dumpUploadFileContents
= $this->dumpUploadFileContents
;
272 $wrapper = new ExportProgressFilter( $this->sink
, $this );
273 $exporter->setOutputSink( $wrapper );
275 if ( !$this->skipHeader
) {
276 $exporter->openStream();
278 # Log item dumps: all or by range
279 if ( $history & WikiExporter
::LOGS
) {
280 if ( $this->startId ||
$this->endId
) {
281 $exporter->logsByRange( $this->startId
, $this->endId
);
283 $exporter->allLogs();
285 } elseif ( is_null( $this->pages
) ) {
286 # Page dumps: all or by page ID range
287 if ( $this->startId ||
$this->endId
) {
288 $exporter->pagesByRange( $this->startId
, $this->endId
, $this->orderRevs
);
289 } elseif ( $this->revStartId ||
$this->revEndId
) {
290 $exporter->revsByRange( $this->revStartId
, $this->revEndId
);
292 $exporter->allPages();
295 # Dump of specific pages
296 $exporter->pagesByName( $this->pages
);
299 if ( !$this->skipFooter
) {
300 $exporter->closeStream();
303 $this->report( true );
307 * Initialise starting time and maximum revision count.
308 * We'll make ETA calculations based an progress, assuming relatively
309 * constant per-revision rate.
310 * @param int $history WikiExporter::CURRENT or WikiExporter::FULL
312 function initProgress( $history = WikiExporter
::FULL
) {
313 $table = ( $history == WikiExporter
::CURRENT
) ?
'page' : 'revision';
314 $field = ( $history == WikiExporter
::CURRENT
) ?
'page_id' : 'rev_id';
316 $dbr = $this->forcedDb
;
317 if ( $this->forcedDb
=== null ) {
318 $dbr = wfGetDB( DB_REPLICA
);
320 $this->maxCount
= $dbr->selectField( $table, "MAX($field)", '', __METHOD__
);
321 $this->startTime
= microtime( true );
322 $this->lastTime
= $this->startTime
;
323 $this->ID
= getmypid();
327 * @todo Fixme: the --server parameter is currently not respected, as it
328 * doesn't seem terribly easy to ask the load balancer for a particular
329 * connection by name.
332 function backupDb() {
333 if ( $this->forcedDb
!== null ) {
334 return $this->forcedDb
;
337 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
338 $this->lb
= $lbFactory->newMainLB();
339 $db = $this->lb
->getConnection( DB_REPLICA
, 'dump' );
341 // Discourage the server from disconnecting us if it takes a long time
342 // to read out the big ol' batch query.
343 $db->setSessionOptions( [ 'connTimeout' => 3600 * 24 ] );
349 * Force the dump to use the provided database connection for database
350 * operations, wherever possible.
352 * @param IDatabase|null $db (Optional) the database connection to use. If null, resort to
353 * use the globally provided ways to get database connections.
355 function setDB( IDatabase
$db = null ) {
356 parent
::setDB( $db );
357 $this->forcedDb
= $db;
360 function __destruct() {
361 if ( isset( $this->lb
) ) {
362 $this->lb
->closeAll();
366 function backupServer() {
369 return $this->server ?
: $wgDBserver;
372 function reportPage() {
376 function revCount() {
381 function report( $final = false ) {
382 if ( $final xor ( $this->revCount %
$this->reportingInterval
== 0 ) ) {
387 function showReport() {
388 if ( $this->reporting
) {
389 $now = wfTimestamp( TS_DB
);
390 $nowts = microtime( true );
391 $deltaAll = $nowts - $this->startTime
;
392 $deltaPart = $nowts - $this->lastTime
;
393 $this->pageCountPart
= $this->pageCount
- $this->pageCountLast
;
394 $this->revCountPart
= $this->revCount
- $this->revCountLast
;
397 $portion = $this->revCount
/ $this->maxCount
;
398 $eta = $this->startTime +
$deltaAll / $portion;
399 $etats = wfTimestamp( TS_DB
, intval( $eta ) );
400 $pageRate = $this->pageCount
/ $deltaAll;
401 $revRate = $this->revCount
/ $deltaAll;
408 $pageRatePart = $this->pageCountPart
/ $deltaPart;
409 $revRatePart = $this->revCountPart
/ $deltaPart;
414 $this->progress( sprintf(
415 "%s: %s (ID %d) %d pages (%0.1f|%0.1f/sec all|curr), "
416 . "%d revs (%0.1f|%0.1f/sec all|curr), ETA %s [max %d]",
417 $now, wfWikiID(), $this->ID
, $this->pageCount
, $pageRate,
418 $pageRatePart, $this->revCount
, $revRate, $revRatePart, $etats,
421 $this->lastTime
= $nowts;
422 $this->revCountLast
= $this->revCount
;
426 function progress( $string ) {
427 if ( $this->reporting
) {
428 fwrite( $this->stderr
, $string . "\n" );